#include "cpage.h"

#include <QFile>
#include <qmessagebox.h>

CPage::CPage(QObject *parent)
    : QObject{parent}
{}

CPage::CPage(const QString &tbname, const QSqlDatabase &db, QObject *parent, const QString &dbname, const QStringList &filterList)
{
    m_db = db;
    m_tbname = tbname;
    m_dbname = dbname;
    if (!dbname.isEmpty()){
        m_db.setDatabaseName(dbname);
    }
    m_model = new QSqlQueryModel(this);
    if (filterList.isEmpty())
    {
        m_filterList.clear();
        m_filterList.append("name")        ;
    }

    else
        m_filterList = filterList;
}


QSqlQueryModel *CPage::model()
{
    return m_model;
}

void CPage::doSearch(const int page, const QString &keyword, const int pageSize)
{

    m_per_page = pageSize;

    //获取总页数
    //1.获取过滤字段
    QString strFilter;
    foreach (auto str, m_filterList) {
        strFilter+= tr("%1 like '%%2%' or ").arg(str,keyword);
    }
    //加上一句"1==2"
    if (strFilter.endsWith(" or ")){
        strFilter += "1=2";
    }
    // qDebug() << strFilter;

    //2.制作sql语句
    QString sql = tr("SELECT count(*) as total FROM %1 WHERE %2;").arg(m_tbname,strFilter);
    // qDebug() << sql;

    //3.查询并获取记录数
    QSqlQuery query(m_db);
    bool ret = query.exec(sql);

    if (!ret){
        qDebug() << query.lastError().text();
        return ;
    }

    query.first();
    int totalRecord = query.value(0).toInt();
    m_total_page = totalRecord / m_per_page;
    if (m_total_page*m_per_page < totalRecord) //看看是不是少算一页
        m_total_page+=1;



    int m_cur_page = (page>m_total_page) ? m_total_page : page;
    if (m_cur_page == -1)
        m_cur_page = m_total_page;



    //设置model
    int fromIndex = (m_cur_page == 1) ? 0 : (m_cur_page-1)*m_per_page-1;
    sql = tr("SELECT * FROM %1 WHERE %2 LIMIT %3,%4;")
              .arg(m_tbname,strFilter)
              .arg(fromIndex)
              .arg(m_per_page);
    qDebug() << sql;
    m_model->setQuery(sql);

    // //遍历所有记录
    // for(int i=0;i<m_model->rowCount();i++)
    //     qDebug() << m_model->record(i);

    //发送信号
    emit searchFinished(m_total_page,m_cur_page,totalRecord);

}

void CPage::exportTable(const QString &filePath)
{

    QJsonArray rows = getRows();
    auto data = QJsonDocument(rows).toJson(QJsonDocument::Indented);
    //写入文件
    QFile f(filePath);
    bool ret = f.open(QIODevice::WriteOnly);

    if (ret){
        ret = f.write(data);
        if (ret){
            QMessageBox::information(nullptr,"yhdn","导出成功");
        }
        f.close();
    }


}

QJsonArray CPage::getRows(QString strCondition)
{
    //声明变量
    bool ret;
    QJsonArray res;

    //获取结果集
    QSqlQuery query(m_db);

    if (strCondition.isEmpty()){
        ret = query.exec(QObject::tr("select * from %1;").arg(m_tbname));
    }
    else
        ret = query.exec(QObject::tr("select * from %1 where %2;").arg(m_tbname,strCondition));


    if (!ret){

        qDebug() << query.lastError().text();
        return QJsonArray();

    }

    //获取字段列表
    auto fieldCount = query.record().count();
    QStringList fieldList ;
    for(int i=0;i<fieldCount;i++){

        fieldList.append(query.record().fieldName(i));
    }

    //遍历结果集 并打包成json数组
    while(query.next()){

        QJsonObject row;

        foreach (auto fieldName, fieldList) {
            row[fieldName] = query.value(fieldName).toString();
        }
        res.append(row);
    }

    return res;

}

QJsonObject CPage::recordToJson(const QSqlRecord &record)
{
    QJsonObject json;

    for(int i=0;i<record.count();i++){

        json[record.fieldName(i)] = record.value(i).toString();
    }

    return json;

}

void CPage::refresh()
{
        //update 数据
    auto sql = m_model->query().lastQuery();
        m_model->setQuery(sql);
}


